package com.ruoyi.project.meal.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.excel.ExcelFillCellMergeStrategy;
import com.ruoyi.common.utils.FileUtil;
import com.ruoyi.common.utils.meal.MealDataUtils;
import com.ruoyi.common.utils.poi.MyHandler;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.meal.domain.MealServiceObjects;
import com.ruoyi.project.meal.domain.MealWorker;
import com.ruoyi.project.meal.vo.MealWorkerVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.meal.domain.MealMilk;
import com.ruoyi.project.meal.service.IMealMilkService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 牛奶上报Controller
 * 
 * @author sky
 * @date 2024-03-20
 */
@Controller
@RequestMapping("/meal/milk")
public class MealMilkController extends BaseController
{
    private String prefix = "meal/milk";

    @Autowired
    private IMealMilkService mealMilkService;

    @GetMapping()
    public String milk()
    {
        return prefix + "/milkCount";
    }

    /**
     * 查询牛奶上报列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MealMilk mealMilk)
    {
        startPage();
        List<MealMilk> list = MealDataUtils.parseMilk( mealMilkService.selectMealMilkList(mealMilk));
        return getDataTable(list);
    }

    /**
     * 牛奶上报详情
     */
    @GetMapping("/detail/{reportDate}/{className}/{campus}")
    public String detail(@PathVariable("reportDate") String reportDate  ,@PathVariable("className") String className  ,@PathVariable("campus") String campus ,ModelMap mmap)
    {
        mmap.put("reportDate", reportDate);
        mmap.put("className", className);
        mmap.put("campus", campus);
        return prefix + "/milk";
    }

    /**
     * 查询牛奶
     */
    @PostMapping("/listCount")
    @ResponseBody
    public TableDataInfo listCount(MealMilk mealMilk)
    {
        startPage();
        List<MealMilk> list = MealDataUtils.parseMilk( mealMilkService.selectMealMilkCount(mealMilk));
        return getDataTable(list);
    }

    @GetMapping("/milkReport")
    public String milkReport()
    {
        return prefix + "/milkReport";
    }

    /**
     * 报表
     */
    @PostMapping("/reportShowList")
    @ResponseBody
    public TableDataInfo reportShowList(MealMilk mealMilk)
    {
        startPage();
        List<MealMilk> list = MealDataUtils.parseMilk( mealMilkService.selectMealMilkReportList( mealMilk));
        return getDataTable(list);
    }

    /**
     * 导出牛奶上报列表
     */
    @Log(title = "牛奶上报", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(MealMilk mealMilk)
    {
        List<MealMilk> list = MealDataUtils.parseMilk( mealMilkService.selectMealMilkList(mealMilk));
        ExcelUtil<MealMilk> util = new ExcelUtil<MealMilk>(MealMilk.class);
        return util.exportExcel(list, "milk");
    }

    /**
     * 导出牛奶日报表
     */
    @PostMapping("/exportDayReport")
    @ResponseBody
    public AjaxResult exportDayReport(MealMilk mealMilk , HttpServletResponse response) throws IOException {
        startPage(0,100000);
        List<MealMilk> list = MealDataUtils.parseMilk( mealMilkService.selectMealMilkCount(mealMilk));
        ExcelUtil<MealMilk> util = new ExcelUtil<MealMilk>(MealMilk.class);
        String templateFileName = FileUtil.getPath() + "excel" + File.separator + "milkDayTotalReport.xlsx";
        String fileName=System.currentTimeMillis() + ".xlsx";
        String fileNamePath= util.getAbsoluteFile(fileName );
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //合并的列学号
        int[] mergeColumnIndex=new int[]{0,2,35};
        // 方案1
        try (ExcelWriter excelWriter = EasyExcel.write(fileNamePath).withTemplate(templateFileName).registerWriteHandler(new ExcelFillCellMergeStrategy(4,mergeColumnIndex)).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<String, Object>();
            excelWriter.fill(map, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(fileName);
    }

    /**
     * 导出牛奶日明细报表
     */
    @PostMapping("/exportDayDetailReport")
    @ResponseBody
    public AjaxResult exportDayDetailReport(MealMilk mealMilk , HttpServletResponse response) throws IOException {
        startPage(0,100000);
        List<MealMilk> list = MealDataUtils.parseMilk( mealMilkService.selectMealMilkList(mealMilk));
        ExcelUtil<MealMilk> util = new ExcelUtil<MealMilk>(MealMilk.class);
        String templateFileName = FileUtil.getPath() + "excel" + File.separator + "milkDayTotalReport.xlsx";
        String fileName=System.currentTimeMillis() + ".xlsx";
        String fileNamePath= util.getAbsoluteFile(fileName );
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //合并的列学号
        int[] mergeColumnIndex=new int[]{0,1,2,35};
        // 方案1
        try (ExcelWriter excelWriter = EasyExcel.write(fileNamePath).withTemplate(templateFileName).registerWriteHandler(new ExcelFillCellMergeStrategy(4,mergeColumnIndex)).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<String, Object>();
            excelWriter.fill(map, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(fileName);
    }

    /**
     * 导出汇总表
     */
    @Log(title = "职工报餐", businessType = BusinessType.EXPORT)
    @PostMapping("/exportReport")
    @ResponseBody
    public AjaxResult exportReport(MealMilk mealMilk , HttpServletResponse response) throws IOException {
        startPage(0,100000);
        List<MealMilk> list =MealDataUtils.parseMilk( mealMilkService.selectMealMilkReportList(mealMilk));
        List<MealMilk> listCont = mealMilkService.selectMealMilkReportTotal(mealMilk);
        ExcelUtil<MealMilk> util = new ExcelUtil<MealMilk>(MealMilk.class);
        String templateFileName = FileUtil.getPath() + "excel" + File.separator + "milkReport.xlsx";
        String fileName=System.currentTimeMillis() + ".xlsx";
        String fileNamePath= util.getAbsoluteFile(fileName );
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //合并的列学号
        int[] mergeColumnIndex=new int[]{0,28};
        // 方案1
        try (ExcelWriter excelWriter = EasyExcel.write(fileNamePath).withTemplate(templateFileName).registerWriteHandler(new ExcelFillCellMergeStrategy(4,mergeColumnIndex)).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<String, Object>();
            if(listCont!=null && listCont.size()>0){
                MealMilk mealMilkTotal=listCont.get(0);
                String mealJson= JSON.toJSONString(mealMilkTotal);
                map= JSON.parseObject(mealJson,Map.class);
            }
            excelWriter.fill(map, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(fileName);
    }

    /**
     * 新增牛奶上报
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存牛奶上报
     */
    @Log(title = "牛奶上报", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(MealMilk mealMilk)
    {
        return toAjax(mealMilkService.insertMealMilk(mealMilk));
    }

    /**
     * 修改牛奶上报
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        MealMilk mealMilk = mealMilkService.selectMealMilkById(id);
        mmap.put("mealMilk", mealMilk);
        return prefix + "/edit";
    }

    /**
     * 修改保存牛奶上报
     */
    @Log(title = "牛奶上报", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MealMilk mealMilk)
    {
        return toAjax(mealMilkService.updateMealMilk(mealMilk));
    }

    /**
     * 删除牛奶上报
     */
    @Log(title = "牛奶上报", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(mealMilkService.deleteMealMilkByIds(ids));
    }

}
